package com.mo.admin.security.handler;

import com.alibaba.fastjson2.JSON;
import com.mo.admin.common.Result;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.security.authentication.*;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import java.io.IOException;

// 认证失败处理器
@Component
public class AuthenticationEntryPointImpl implements AuthenticationEntryPoint {

    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException {
        String message = null;

        // 根据异常类型设置相应的错误信息
        if (authException instanceof BadCredentialsException) {
            message = "用户名或密码错误";
        } else if (authException instanceof InsufficientAuthenticationException) {
            message = "Full authentication is required to access this resource";
        } else if (authException instanceof AuthenticationServiceException) {
            message = "认证服务异常";
        } else if (authException instanceof AccountExpiredException) {
            message = "账号已过期";
        } else if (authException instanceof CredentialsExpiredException) {
            message = "密码已过期";
        } else if (authException instanceof LockedException) {
            message = "账号被锁定";
        } else if (authException instanceof DisabledException) {
            message = "账号被禁用";
        } else {
            message = "登录认证失败";
        }

        // 此处可以记录日志
        response.setContentType("application/json;charset=utf-8");
        response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
        Result result = Result.error(message, HttpServletResponse.SC_UNAUTHORIZED);
        response.getWriter().write(JSON.toJSONString(result));
    }
}